package com.hydra.auth.config.points;

import com.hydra.auth.config.exception.BootOAuth2Exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer;
import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.web.HttpRequestMethodNotSupportedException;

/**
 * 自定义异常
 */
@Slf4j
public class OAuth2WebResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {

    private final ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) {
        Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(e);
        Exception ase = (OAuth2Exception)this.throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
        if (ase != null) {
            return this.handleOAuth2Exception(((OAuth2Exception)ase).getHttpErrorCode(), (OAuth2Exception)ase);
        } else {
            ase = (AuthenticationException)this.throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
            if (ase != null) {
                return this.handleOAuth2Exception(401, new OAuth2Exception(e.getMessage(), e));
            } else {
                ase = (AccessDeniedException)this.throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
                if (ase != null) {
                    return this.handleOAuth2Exception(403, new OAuth2Exception(ase.getMessage(), ase));
                } else {
                    ase = (HttpRequestMethodNotSupportedException)this.throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
                    if(ase != null){
                        return this.handleOAuth2Exception(405, new OAuth2Exception(ase.getMessage(), ase));
                    }else{
                        return this.handleOAuth2Exception(500, new OAuth2Exception(e.getMessage(), e));
                    }
                }
            }
        }
    }

    private ResponseEntity<OAuth2Exception> handleOAuth2Exception(int code, OAuth2Exception e) {
        int status = e.getHttpErrorCode();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        if (status == HttpStatus.UNAUTHORIZED.value() || e instanceof InsufficientScopeException) {
            headers.set("WWW-Authenticate", String.format("%s %s", "Bearer", e.getSummary()));
        }
        BootOAuth2Exception bootOAuth2Exception = new BootOAuth2Exception(code, e.getMessage(), e);
        return new ResponseEntity<>(bootOAuth2Exception, headers, HttpStatus.valueOf(status));
    }

}
